package com.peng.leetcode.tree;

import java.util.List;

/**
 * ConstructMaximumBinaryTree
 *
 * @author: lupeng6
 * @create: 2021/2/4 17:41
 */
public class ConstructMaximumBinaryTree {

    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 6, 0, 5};
        TreeNode treeNode = new ConstructMaximumBinaryTree().constructMaximumBinaryTree(nums);
        List<Integer> integers = TreeMain.layerOrder(treeNode);
        System.out.println(integers);
    }

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        int index = findMaxIndex(nums, 0, nums.length);
        TreeNode root = new TreeNode(nums[index]);
        root.left = dfs(nums, 0, index);
        root.right = dfs(nums, index + 1, nums.length);
        return root;
    }

    TreeNode dfs(int[] nums, int start, int end) {
        if (start >= end) {
            return null;
        }
        int index = findMaxIndex(nums, start, end);
        TreeNode root = new TreeNode(nums[index]);
        root.left = dfs(nums, start, index);
        root.right = dfs(nums, index + 1, end);
        return root;
    }

    int findMaxIndex(int[] nums, int start, int end) {
        int max = nums[start];
        int index = start;
        for (int i = start; i < end; i++) {
            if (nums[i] > max) {
                max = nums[i];
                index = i;
            }
        }
        return index;
    }
}
